<template>
  <div :class="$style['countdown-wrap']">
    <slot>
      <Field
        v-model="result"
        v-on="$listeners"
        v-bind="$attrs"
        :class="$style['countdown-input']"
      />
    </slot>
    <span
      :class="[
        classBtn,
        $style['countdown-btn'],
        { [`${$style['disabled']}`]: !flag },
      ]"
      @click="start"
      >{{ btnText }}<template v-if="!flag">({{ cunt }}s)</template></span
    >
  </div>
</template>

<script>
import { Field } from "vant";
export default {
  name: "countdownVerification",
  props: {
    params: Function,
    value: String,
    dur: {
      default: 60,
    },
    btnText: {
      default: "发送验证码",
    },
    apiName: {
      default: "smsCode",
    },
    id: {
      default: "countdown",
    },
    classBtn: {
      default: "",
    },
  },
  model: {
    prop: "value",
    event: "valueChange",
  },
  data() {
    let cunt = this.dur,
      _cunt = window.sessionStorage.getItem(`cunt${this.id}`);
    if (!isNaN(Number(_cunt)) && Number(_cunt) > 0) cunt = Number(_cunt);
    return {
      timer: null,
      cunt,
      flag: true,
    };
  },
  watch: {
    cunt(val) {
      if (!isNaN(Number(val)))
        window.sessionStorage.setItem(`cunt${this.id}`, val);
    },
  },
  computed: {
    result: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("valueChange", val);
      },
    },
  },
  components: { Field },
  mounted() {
    if (this.cunt > 0 && this.cunt < this.dur) this.countdown();
  },
  methods: {
    //点击发送验证码按钮
    start() {
      if (this.flag) {
        this.send();
      }
    },
    //倒计时
    countdown() {
      if (this.cunt >= 0) {
        this.flag = false;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.cunt--;
          this.countdown();
        }, 1000);
      } else {
        this.reset();
      }
    },
    //发送验证码
    async send() {
      let params = (this.params && this.params()) || {};
      if (params instanceof Promise) params = await params;
      if (params === false) return;
      let req = new Promise((r) => {
        setTimeout(() => {
          r();
        }, 1000);
      });
      // let req = this.$api("post", this.apiName, {
      //   ...(params ? params : {}),
      // });
      req.then((res) => {
        this.countdown();
        this.$emit("success", res);
        this.$toast.success("验证码发送成功！");
        return res;
      });
      return req;
    },
    //重置
    reset() {
      this.flag = true;
      this.cunt = this.dur;
      setTimeout(() => {
        window.sessionStorage.removeItem(`cunt${this.id}`);
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style module scoped lang="scss">
.countdown-wrap {
  display: flex;
  align-items: center;
  padding-right: 14px;
}
.countdown-btn {
  width: 100px;
  font-size: 14px;
  white-space: nowrap;
  color: $themeColor;
  border-left: 1px solid $themeColor;
  margin-left: 0.5em;
  padding-left: 0.5em;
  &.disabled {
    opacity: 0.6;
  }
}
.countdown-input {
  margin-bottom: 0;
}
</style>
